import json

from django.db.models import Avg, Count, Min, Max, Sum
from django.http import HttpResponse
from django.shortcuts import render
import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "green.settings")
django.setup()

# render请求
from green import models


def three(request):
    return render(request, "three/three.html")


def initBigJsonForThree(request):
    # 各种类汽车总数量变化
    bigJson = {}
    tempList = []
    yearList = [2016, 2017, 2018]
    carList = ["private", "cargo", "manned"]
    for year in yearList:
        cars = {'year': year}
        for item in carList:
            queryData = models.Cars.objects.all().aggregate(value=Sum('number_' + str(year) + item))
            # print("单次查询" + item, queryData)

            cars[item] = queryData['value']
        tempList.append(cars)

    bigJson['total'] = tempList
    # print(bigJson)
    queryData = models.Cars.objects.all().values()

    for cityData in queryData:
        tempList = []
        city = cityData['provence']
        for year in yearList:
            cars = {'year': year}
            for item in carList:
                cars[item] = cityData['number_' + str(year) + item]
            tempList.append(cars)
        bigJson[city] = tempList
    print(bigJson)

    # 将bigjson保存为文件
    s = json.dumps(bigJson)
    f = open('../../templates/three/showThree.json', 'w', encoding='UTF-8')
    f.write(s)
    f.close()
    print("构造bigjson.json成功！")
    return HttpResponse("构造成功！")


def showThree(request):
    city = request.GET.get('cityName')
    print(city)
    if city is None:
        f = open('templates/three/showThree.json', 'r', encoding='utf-8')
        bigJson = f.read()
        f.close()
        data = json.loads(bigJson)['total']
        data = {'data': data}
        response = HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
        return response
    else:
        f = open('templates/three/showThree.json', 'r', encoding='utf-8')
        bigJson = f.read()
        f.close()
        data = json.loads(bigJson)[city]
        data = {'data': data}
        response = HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
        return response


if __name__ == '__main__':
    initBigJsonForThree(0)
